import { ShelfCourse } from '@/api/Shelf';
import { useReactive } from 'ahooks';
import { App, Button, Drawer, Modal } from 'antd';
import { useRef, useState } from 'react';
import type { YmColumnsType } from 'ym-design';
import { YmTable } from 'ym-design';
import { ShelfCourseUpperRef, ShelfUpperModalContentForCourse } from '../../../UpperContent';
import { CourseDetail, CourseDetailProps } from '../../Detail';
type TableRecord = ShelfCourse;
type SearchForm = {
  courseName: string;
};

interface ListPorps {
  // 新增编辑事件
  onAddEdit?(value?: {
    courseId?: string;
    faceImg?: string;
    courseName?: string;
    learnEndTime?: string;
    learnStartTime?: string;
  }): void;
  // 打开弹窗事件
  onDetail?(): Promise<boolean>;
  // 删除事件
  onDelete?(): Promise<boolean>;
}

export function List({ onAddEdit }: ListPorps) {
  const { modal } = App.useApp();
  const [columns] = useState<YmColumnsType<TableRecord>>([
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: 200,
    },
    {
      title: '数量',
      dataIndex: 'num',
      key: 'num',
      width: 200,
    },
    {
      key: '_operate',
      title: '操作',
      width: 140,
    },
  ]);
  const [tableDep, _reFreshTable] = useState<number>();
  const reFreshTable = () => _reFreshTable(Math.random());
  const upperExtram = useReactive<{ guid?: string }>({ guid: undefined });
  const upperRef = useRef<ShelfCourseUpperRef>(null);
  const detailsPorps = useReactive<{ props?: CourseDetailProps }>({});

  return (
    <div className="safe_boss_pagelr">
      <YmTable<TableRecord, SearchForm>
        searchForm={{
          formItems: [
            {
              label: '课程名称',
              name: 'courseName',
              valueType: {
                type: 'input',
              },
            },
          ],
          span: 6,
        }}
        columns={columns}
        request={async ({ page }, form) => {
          console.log('请求发出去了么');
          const { current = 1, pageSize = 10 } = page ?? {};
          const data = await ShelfCourse.unShelfList(current, pageSize, form);
          console.log(data, '---再次检查结果');
          return data;
        }}
        requestOptions={{
          reFreshDep: [tableDep],
          defaultPageSize: 20,
        }}
        toolBar={{
          prefixNode: (
            <Button
              type="primary"
              onClick={() => {
                onAddEdit?.();
              }}
            >
              新增课程
            </Button>
          ),
        }}
        operate={[
          {
            text: '编辑',
            key: 'edit',
            onClick(record) {
              onAddEdit?.({
                courseId: record.guid,
                faceImg: record.cover,
                courseName: record.name,
                learnEndTime: record.learnEndTime,
                learnStartTime: record.learnStartTime,
              });
            },
          },
          {
            text: '详情',
            key: 'detail',
            onClick(record) {
              detailsPorps.props = {
                guid: record.guid,
                name: record.name,
                createTime: record.createTime,
              };
            },
          },
          {
            text: '删除',
            key: 'delete',
            onClick(record) {
              modal.confirm({
                title: '提示',
                content: `确定要删除【${record.name}】吗`,
                async onOk() {
                  await ShelfCourse.delete(record.guid);
                  reFreshTable();
                },
              });
            },
          },
          {
            text: '上架',
            key: 'listing',
            onClick(record) {
              upperExtram.guid = record.guid;
            },
          },
        ]}
        rowKey="guid"
      />
      <Modal
        width={480}
        title="上架"
        open={Boolean(upperExtram.guid)}
        onCancel={() => (upperExtram.guid = undefined)}
        centered
        destroyOnClose
        maskClosable={false}
        onOk={async () => {
          const result = await upperRef.current?.submit();
          await ShelfCourse.shelf.upper({ ...upperExtram, ...result });
          upperExtram.guid = undefined;
          reFreshTable();
        }}
      >
        <ShelfUpperModalContentForCourse ref={upperRef}></ShelfUpperModalContentForCourse>
      </Modal>
      <Drawer
        width={800}
        open={Boolean(detailsPorps.props)}
        title="详情"
        onClose={() => {
          detailsPorps.props = undefined;
        }}
      >
        <CourseDetail {...detailsPorps.props} />
      </Drawer>
    </div>
  );
}
